package grid;

public class Grid3DMap {
	public static void mapLinear(Grid3DFloat sourcegrid, Grid3DFloat targetgrid) {
		for (int x = 0; x < targetgrid.nX ; x++) {
			for (int y = 0; y < targetgrid.nY ; y++) {
				for (int z = 0; z < targetgrid.nZ; z++) {

					float sourceX = (x * 1f / targetgrid.nX) * sourcegrid.nX;
					float sourceY = (y * 1f / targetgrid.nY) * sourcegrid.nY;
					float sourceZ = (z * 1f / targetgrid.nZ) * sourcegrid.nZ;
					int cX0 = (int) (sourceX);
					int cY0 = (int) (sourceY);
					int cZ0 = (int) (sourceZ);
					int cX1 = cX0 + 1;
					int cY1 = cY0 + 1;
					int cZ1 = cZ0 + 1;
					cX1 = Math.min(cX1, sourcegrid.nX - 1);
					cY1 = Math.min(cY1, sourcegrid.nY - 1);
					cZ1 = Math.min(cZ1, sourcegrid.nZ - 1);

					float v000 = sourcegrid.get(cX0, cY0, cZ0);
					float v100 = sourcegrid.get(cX1, cY0, cZ0);
					float v010 = sourcegrid.get(cX0, cY1, cZ0);
					float v110 = sourcegrid.get(cX1, cY1, cZ0);
					
					float v00 = map(sourceX, cX1, cX0, v000, v100);
					float v10 = map(sourceX, cX1, cX0, v010, v110);
					
					if (v00>1)System.out.println(v000+" "+v100);
					
					float v0 = map(sourceY, cY1, cY0, v00, v10);
					
					
					float v001 = sourcegrid.get(cX0, cY0, cZ1);
					float v101 = sourcegrid.get(cX1, cY0, cZ1);
					float v011 = sourcegrid.get(cX0, cY1, cZ1);
					float v111 = sourcegrid.get(cX1, cY1, cZ1);
					
					float v01 = map(sourceX, cX1, cX0, v001, v101);
					float v11 = map(sourceX, cX1, cX0, v011, v111);

					float v1 = map(sourceY, cY1, cY0, v01, v11);
					
					
					float v = map(sourceZ, cZ1, cZ0, v0, v1);
					
					
					//if (v>1||v<0)
						
						//System.out.println(x+" "+y+" "+z);
					targetgrid.set(x, y, z, v);

				}
			}
		}
	}
	
	public static float map(float v, float s1, float s2, float t1, float t2){
		if (s1==s2)return t1;
		return (t2-t1)*(v-s1)/(s2-s1)+t1;
	}
}
